from selenium import webdriver # 浏览器自动控制
from pyquery import PyQuery as pq # html解析库
import re
import requests
from selenium.common.exceptions import TimeoutException # 超时报错
from selenium.webdriver.support.ui import WebDriverWait # 获取webdriver实例，并在等待几秒后超时
from selenium.webdriver.common.by import By # By后面加用什么定位，比如By_CSS_SELECTOR就是用css定位
from selenium.webdriver.support import expected_conditions as EC # 判断元素是否出现在网页中或者判断动态等待页面上元素出现或者消失
from config import *
import pymongo

client = pymongo.MongoClient(MONGO_URL)
db = client[MONGO_DB]

browser = webdriver.Chrome()
wait = WebDriverWait(browser, 10) # 设置等待时间为10秒，超过10秒就超时错误


def search():
    '''
    搜索页面，定位搜索框，并输入搜索内容，定位搜索按钮，并点击搜索
    '''
    try: 
        browser.get('https://www.taobao.com/')
        input = wait.until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "#q"))
        ) # 在十秒内确认用css选择起选择的id=q的元素出没出现
        submit = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,
                    "#J_TSearchForm > div.search-button > button"))) # 在十秒内确认用css选择器选择的按钮可不可以点击
        input.send_keys('情趣透视')
        submit.click()
        total =
        wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"#mainsrp-pager>
            div > div > div > div.total")))# 在十秒内确认css选择器选择的元素初没出现
        get_products()
        return total.text
    except TimeoutException:
        return search()

def next_page(page_number):
    '''
    换页，在输入框内输入页码，并且点击确认
    '''
    try:
        input = wait.until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "#mainsrp-pager > div > div > div > div.form > input"))
        )
        submit = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"#mainsrp-pager > div > div > div > div.form >span.btn.J_Submit")))
        input.clear()
        input.send_keys(page_number)
        submit.click()
        wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR,
                '#mainsrp-pager>div > div > div > ul > li.item.active > span'),
                str(page_number)))
        get_products()
    except TimeoutException:
        next_page(page_number)


def get_products():
    '''
    获取每个商品的详细信息，名字、价格等
    '''
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,
    "#mainsrp-itemlist .items .item")))
    html = browser.page_source
    doc = pq(html)
    items = doc('#mainsrp-itemlist .items .item').items()
    for item in items:
        products = {
                'img':item.find('.pic .img').attr('src'),
                'price':item.find('.price').text(),
                'deal':item.find('.deal-cnt').text()[:-3],
                'title':item.find('.title').text(),
                'shop':item.find('.shop').text(),
                'location':item.find('.location').text(),
                }
        print(products)
        save_to_mongo(products)

def save_to_mongo(result):
    '''
    保存到数据库
    '''
    try:
        if db[MONGO_TABLE].insert_one(result):
            print('保存mongodb成功', result)
    except Exception:
        print('保存mongodb失败', result)

def main():
    '''
    主函数，在这里吗调用上面的方法
    '''
    total = search()
    total = int(re.compile('(\d+)').search(total).group(1))
    for i in range(2, total + 1):
        next_page(i)
    browser.close()

if __name__ == '__main__':
    main()
